/**
 * Task 操作器
 * 
 * jQuery-based
 * Objects-based
 * 
 * @author Bevis.Zhao
 */
(function($){
	
	var taskIntegrator = {
		tasks_data : [],
		load : function(json){
			taskIntegrator.addEventListener('li.task_template');
			
			// 如果task list长度为0, 初始化为1
			this.initTasks(json);
			this.createTask(this.tasks_data);
		},
		// TODO 操作记录
		history : {
			
		},
		_saveTasks : function(){
			$.cookie('gtdoffice_cookie', $.toJSON(taskIntegrator.tasks_data));
		},
		_getCookieTasks : function(){
			return false ? null : $.cookie('gtdoffice_cookie');
		},
		_removeCookieTasks : function(){
			$.cookie('gtdoffice_cookie', null);
		},
		newTask : function(){
			return  task = {
				id : Objects.guid(),
				caption : ''
			};
		},
		initTasks : function(json){
			var siftTasks = [];
			for(var i = 0; i < json.length; i++){
				var task = json[i];
				if(!task || !task.id) continue;
				siftTasks.push(task);
				siftTasks[task.id] = task;
			}
			// 如果没有列表, 则初始化空task
			if(siftTasks.length == 0)
				siftTasks.push(taskIntegrator.newTask());
			taskIntegrator.tasks_data = siftTasks;
		},
		getTemplateTask : function(){
			return $(Metadata.xpath.task_template).clone()
				.removeClass('task_template');
		},
		getTaskIndex : function(id){
			for(var i = 0 ; i < taskIntegrator.tasks_data.length; i++){
				if(taskIntegrator.tasks_data[i].id == id)
					return i;
			}
			return -1;
		},
		/**
		 * 
		 * @param {JSON} json
		 * @param {xPath/jQuery} relativeTask
		 * 	在relativTask前创建新Task
		 */
		createTask : function(tasks_data, relativeTask){
			// 载入模板
			var template = taskIntegrator.getTemplateTask();
			if(!tasks_data.slice){
				var tmpTasks = [];
				tmpTasks.push(tasks_data);
				tasks_data = tmpTasks;
			}
			// 获取相对task位置
			var relativeTaskIndex = relativeTask ? taskIntegrator.getTaskIndex($(relativeTask)[0].task_id) : null;
			relativeTaskIndex = relativeTaskIndex == -1 ? null : relativeTaskIndex;
			// 创建Task空列表 
			var tasks = $('_');
			for(var i = 0; i < tasks_data.length; i++){
				var data = tasks_data[i];
				var id = data.id;
				var one = template.clone();
				// 更新tasks_data
				dataIndex = Objects.indexOfArray(taskIntegrator.tasks_data, data);
				if(dataIndex == -1)
					Objects.join(taskIntegrator.tasks_data, data, relativeTaskIndex);
				else
					taskIntegrator.tasks_data[dataIndex] = data;
				taskIntegrator.tasks_data[id] = data;
				one[0].task_id = id;
				
				// 初始化task显示内容
				one.find('div.caption').html(data.caption);
				tasks = tasks.add(one);
			}
		
			// 添加事件监听
			this.addEventListener(tasks);
			// 添加到HTML  如果没有设定(!relativeTask is true), 默认在列表尾部新建task
			tasks.insertBefore(relativeTask || Metadata.xpath.task_template)
			// 定焦最后一个task
			taskIntegrator.focusTask(tasks.get(tasks.size() - 1));
			return tasks;
		},
		// TODO 修改Task
		updateTask : function(id, caption, task_data){
			task_data = task_data || {id : id};
			task_data.caption = caption;
			// 修改task内容
			taskIntegrator.tasks_data[id] = task_data;
			taskIntegrator.tasks_data[taskIntegrator.getTaskIndex(id)] = task_data;
			taskIntegrator._saveTasks();
			// TODO 修改详细内容
		},
		// TODO 删除Task
		deleteTask : function(task_wrapper){
			task_wrapper = $(task_wrapper);
			var id = $(task_wrapper)[0].task_id;
			taskIntegrator.tasks_data[id] = null;
			taskIntegrator.tasks_data[taskIntegrator.getTaskIndex(id)] = null;
			task_wrapper.remove();
		},
		focusTask : function(task){
			$('div.caption',task).trigger('click');
		},
		toogleMini : function(wrapper){
			$('.bar_sprites', wrapper).trigger('mouseout');
			var caption_editor = $('textarea', wrapper);
			var caption_div = $('div.caption', wrapper);
			$(caption_editor).hide().fadeOut(600, function(){
				caption_editor.remove();
				caption_div.fadeIn(600);
			});
		},
		/**
		 * 添加事件监听
		 * @param {jQuery.li} task_wrapper
		 */
		addEventListener : function(task_wrapper){
			for(var f in this.eventListeners ){
				if(typeof this.eventListeners[f] === 'function' && !/^_.*/.test(f))
					this.eventListeners[f].call(this, task_wrapper);
			}
		},
		eventListeners : {
			createable : function(tasks){
				$('.task_spare', tasks).click(function(){
					var $self = $(this);
					taskIntegrator.createTask(taskIntegrator.newTask(), $self.parent());
					$self.trigger('mouseout');
				});
			},
			editable : function(tasks){
				$('div.caption', tasks).click(function(){
					var caption_div = $(this);
					var taskWrapper = caption_div.parents('li:eq(0)');
					var div_caption = $(this).hide();
					var editor = div_caption.prev('textarea.caption');
					editor = editor.length != 0 ? editor : $('<textarea/>').addClass('caption')
						.val(taskIntegrator.tasks_data[taskWrapper[0].task_id].caption || '')
						.insertBefore(div_caption)
						.blur(taskIntegrator.eventListeners._editable.caption_editor_blur)
						.keydown(taskIntegrator.eventListeners._editable.caption_editor_hotkey)
						.autogrow({lineHeight: 16});
					editor.focus();
				});
			},
			_editable : {
				caption_editor_blur : function(){
					var $self = $(this);
					var caption = this.value;
					var task_wrapper = $self.parents('li:eq(0)');
					var trimmedCaption = caption.toString().replace(/\r\n/gi, ' ');
					var caption_div = $self.nextAll('div.caption')
						.text(trimmedCaption);
					taskIntegrator.updateTask(task_wrapper[0].task_id, caption);
					taskIntegrator.toogleMini(task_wrapper);
				},
				caption_editor_hotkey : function(e){
					var $self = $(this);
					var task_wrapper = $self.parents('li:eq(0)');
					switch(e.keyCode){
					// ESC 取消焦点
					case 27 :
						$self.blur();
						break;
					// Tab / Shift + Tab
					case 9 :
						var next = task_wrapper.next();
						var prev = task_wrapper.prev();
						$('textarea.caption', task_wrapper).trigger('blur');
						if (e.shiftKey) {
							if (prev.length == 0) 
								$('.task_spare', task_wrapper).trigger('click');
							else 
								taskIntegrator.focusTask(prev);
						} else {
							if (next.is('.task_template')) 
								$('.task_spare', next).trigger('click');
							else 
								taskIntegrator.focusTask(next);
						}
						break;
					// 回车 Ctrl + Alt + Enter : toogleMini
					case 13 :
						if (e.ctrlKey && e.altKey) {
							$self.blur();
							taskIntegrator.toogleMini(task_wrapper);
							break;
						}
						return ;
					// 当没有数据时, 删除当前task
					case 8:
					case 46:
						if($self.val() == ''){
							var next = task_wrapper.next().not('.task_template');
							var prev = task_wrapper.prev();
							if(prev.length != 0){
								$('textarea.caption', task_wrapper).trigger('blur');
								taskIntegrator.deleteTask(task_wrapper);
								if(next.length == 0 || e.keyCode == 8)
									taskIntegrator.focusTask(prev);
								else
									taskIntegrator.focusTask(next);
							} else{
								if(next.length != 0 && e.keyCode == 46){
									taskIntegrator.deleteTask(task_wrapper);
									taskIntegrator.focusTask(next);
								}
							}
							break;
						}
						return ;
					default : 
						return;	
					}
					return false;
				}
			}
		}
	};
	
	window.taskIntegrator = taskIntegrator;
	
})(jQuery);